/*   
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.   
 *   
 * This software is the confidential and proprietary information of   
 * DMGIS. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with DMGIS.   
 *   
 */
package com.dmgis.qxfw.dataservice.businessservice.common.controller;


import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.user_table;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.SmallScaleStation;
import com.dmgis.qxfw.dataservice.businessservice.common.service.IConfigService;
import com.dmgis.qxfw.dataservice.businessservice.common.util.ImageUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.JsonUtil;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.commonservice.common.DbConfig;
import com.dmgis.qxfw.dataservice.commonservice.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.commonservice.utils.MD5Utils;
import com.dmgis.qxfw.dataservice.commonservice.utils.RedisUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class is used for 公共信息查询
 * 
 * @author dsq
 * @version 1.0, 2018年6月27日 上午8:18:09
 */
@Controller
@RequestMapping("/common")
public class CommInfoController {
	@Resource
	private IConfigService configService;

	ProcessRequestController pc = new ProcessRequestController();
	@RequestMapping("/GetuserName")
	@ResponseBody
	public Object GetuserName(HttpServletRequest request, Model model) {
		String name = "";
		String newName = "";
		List<user_table> listData = new ArrayList<user_table>();
		String userName = request.getParameter("username");
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		// 拼接where字段
		StringBuilder strWhere = new StringBuilder();
		strWhere.append(String.format("username='%s'", userName));
		strWhere.append("and servicewebaddress like '%cdproweb%'");
		selectRequest.setParam(strWhere.toString());
		try {
			selectParam.put("method", "user_table");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<user_table>>() {
			});

			name = listData.get(0).getReservoirname();
			if(name.contains("水利局")){
				newName = StringUtils.substringBefore(name,"水利局");
			}else{
				newName = name;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return newName;
	}
	/**
	 * 通过username生成token并且存入redis设置过期时间3小时
	 *
	 * @return String
	 * @Param username
	 */
	String generateToken(String userName) {
		//userName+时间戳+随机字符串 MD5加密
		long currentTime = System.currentTimeMillis();
		//生成指定长度的随机字符串
		String randomStr = RandomStringUtils.randomAlphanumeric(10);
		StringBuilder encodeStr = new StringBuilder();
		encodeStr.append(userName).append(currentTime).append(randomStr);
		//使用Md5加密生成token
		String token = MD5Utils.MD5Encode(encodeStr.toString(), "utf-8");
		//将token存储到redis并且设置过期时间为3小时
		Jedis jedis = RedisUtil.getJedis();
		jedis.set(token,Long.toString(System.currentTimeMillis()), "NX","EX", 3*3600);
		return token;
	}



	@RequestMapping("/out")
	@ResponseBody
	public void out(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			HttpSession session = request.getSession();
			session.invalidate();
//			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
//					+ request.getContextPath();
//			request.getRequestDispatcher(basePath).forward(request,response);
//		 	response.sendRedirect(basePath);

		}catch (Exception e){
			e.printStackTrace();
		}
	}






	/**
	 * 城市站点添加，自动站添加
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @author dsq
	 * @throws
	 * @date 2018年6月27日
	 */
	@RequestMapping("/cityStaList")
	@ResponseBody
	public String cityStaList(HttpServletRequest request, Model model){
		String method = request.getParameter("method");
		List<SmallScaleStation> cityStaList, townStaList;
		cityStaList = configService.getCitySta();// 城市站点
		townStaList = configService.getTownStaList();// 乡镇
		String strCityList = "<table  style=\"margin-bottom: 20px\">";
		for (SmallScaleStation citysStation : cityStaList) {
			strCityList += "<tr><td width=\"52\"><a sid=\"" + citysStation.getStationID().trim()
					+ "|1\" onclick=\"selCity(" + citysStation.getLongitude() + "," + citysStation.getLatitude()
					+ ",this)\" class=\"black\" href=\"javascript:void(0);\">";
			strCityList += citysStation.getStationName() + "</a></td><td>";
			for (SmallScaleStation townStation : townStaList) {
				if (townStation.getCounty().equals(citysStation.getStationName())) {
					String townName = townStation.getStationName();
					if (method.equals("City")) { // 自动站点
						if (townName.contains("乡")) {
							townName = townName.substring(0, townName.indexOf('乡') + 1);
						}
						if (townName.contains("镇")) {
							townName = townName.substring(0, townName.indexOf('镇') + 1);
						}
					}
					strCityList += "<a  sid=\"" + townStation.getStationID().trim() + "|0\" onclick=\"selCity("
							+ townStation.getLongitude() + "," + townStation.getLatitude()
							+ ",this)\" href=\"javascript:void(0)\" name=\"" + townName + "\">" + townName + "</a>";
				}
			}
			strCityList += "</td></tr>";
		}
		strCityList += "</table>";
		return strCityList;
	}

	/**
	 * 预报站点列表
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @author dsq
	 * @date 2018年6月27日
	 */
	@RequestMapping("/YuBaoStation")
	@ResponseBody
	public String townshipList(HttpServletRequest request, Model model) {
		String result = "";
		List<SmallScaleStation> cityStations = configService.getCitySta();// 城市站
		for (SmallScaleStation cityStation : cityStations) {
			result += "<option value='" + cityStation.getStationID().trim() + "|1'>"
					+ cityStation.getStationName().trim() + "(城市站)</option>";
		}

		List<SmallScaleStation> townshipStations = configService.getTownStaList(); // 获取所有城镇站点
		for (SmallScaleStation townshipStation : townshipStations) {
			String townName = townshipStation.getStationName();
			if (townName.contains("乡")) {
				townName = townName.substring(0, townName.indexOf('乡') + 1);
			}
			if (townName.contains("镇")) {
				townName = townName.substring(0, townName.indexOf('镇') + 1);
			}
			result += "<option value='" + townshipStation.getStationID() + "|0'>" + townName + "</option>";
		}
		return result;
	}

	/**
	 * 实况站点信息
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @author dsq
	 * @date 2018年6月28日
	 */
	@RequestMapping("/ShiKuangStation")
	@ResponseBody
	public String shikuangStaList(HttpServletRequest request, Model model) {
		String result = "";
		List<SmallScaleStation> shikuangStations = configService.getTownStaList(); // 获取实况站点列表
		for (SmallScaleStation smallScaleStation : shikuangStations) {
			String strName = smallScaleStation.getStationName().trim();
			if (strName.equals("高坪")) {
				result += "<option value='" + smallScaleStation.getStationID() + "' selected = 'selected'>"
						+ smallScaleStation.getStationName() + "</option>";
			} else {
				result += "<option value='" + smallScaleStation.getStationID() + "'>"
						+ smallScaleStation.getStationName() + "</option>";
			}
		}
		return result;
	}

	@RequestMapping("/GetMap")
	@ResponseBody
	public String getMap(HttpServletRequest request, Model model) {
		String row = request.getParameter("row");
		String col = request.getParameter("col");
		String level = request.getParameter("level");
		String type = request.getParameter("type");
		String filePath = "map/" + level + "/" + row + "/" + col + "." + type;
		String servicePath = request.getSession().getServletContext().getRealPath("/") + filePath;
		File imgFile = new File(servicePath);
		if (imgFile.exists()) {
			ImageUtil.transferAlpha(servicePath);
		}
		System.out.println(imgFile.exists());
		return filePath;
	}
}
